package www.dianbaozu.com.ui.find.searchServer

import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import www.wen.com.common.R
import www.wen.com.common.lib.base.module.BaseAbsViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.repository.AppDataManager
import www.wen.com.common.lib.extension.getString

class SearchServerViewModel @ViewModelInject constructor(appDataManager: AppDataManager) :
    BaseAbsViewModel<ServerListEntity, ServerEntity>(appDataManager) {

    override suspend fun requestListData(requiredParameter: Any): Result<ServerListEntity> =
        appDataManager.requestServerList(requiredParameter as String,null,mPage,mLimit)

    override fun dataConversion(data: ServerListEntity): List<ServerEntity> {
        return  data.content
    }

    /**
     * 把服务器加入预览
     */
    fun requestServerPreview(
            serverId: String,
            action: ((ServerSelfListEntity.Content) -> Unit)? = null,
    ) {
        viewModelScope.launch {
            loading.value = UiStateCustom(
                    stateData = LoadingDialog(
                            getString(R.string.loading),
                            LoadingDialogStateType.LOADING
                    )
            )
            val result = appDataManager.requestServerPreview(serverId)
            if (result is Result.Success) {
                loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                                tip = "",
                                loadingDialogStateType = LoadingDialogStateType.SUCCESS,
                                isShowDialogTip = false,
                                isShowToastTip = false,
                        )
                )
                action?.invoke(result.data)
            } else if (result is Result.Error) {
                loading.value = UiStateCustom(
                        stateData = LoadingDialog(
                                tip = result.exception.message!!,
                                loadingDialogStateType = LoadingDialogStateType.ERROR,
                                isShowDialogTip = false,
                                isShowToastTip = true
                        )
                )
            }
        }
    }

}